<template>
    <container class="model">
        <toolbar>
            <div class="right" slot="right">
                <config-select v-model="activeConfig" @select="handleConfigSelect"></config-select>
                <el-button size="mini" type="success" plain @click="templateDialog.visible = true">模板</el-button>
            </div>
        </toolbar>

        <el-card class="main">
            <operation>
                <base-select slot="left" class="databases-select"
                             v-model="activeDatabase" :options="databaseOptions"
                             size="mini" @change="handleDatabaseChange"></base-select>
            </operation>

            <el-table :data="list">
                <el-table-column prop="TABLE_NAME" label="表名" align="right"></el-table-column>
                <el-table-column prop="TABLE_COMMENT" label="注释" align="right"></el-table-column>
                <el-table-column align="right">
                    <template slot="header" slot-scope="scope">
                        <el-input v-model="search" size="mini" placeholder="输入表名关键字搜索"/>
                    </template>
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" plain @click="buildClick(scope.row)">构建</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>

        <!--dialog-->
        <template>
            <model-template-dialog
                    v-if="templateDialog.visible"
                    v-model="templateDialog.visible"
                    :default-template="templateDialog.defaultTemplate"
                    :cache-key="templateDialog.cacheKey">

            </model-template-dialog>
            <model-build-dialog
                    v-if="buildDialog.visible"
                    v-model="buildDialog.visible"
                    :table="buildDialog.table"
                    :columns="buildDialog.columns">

            </model-build-dialog>
        </template>
    </container>
</template>

<script type="text/ecmascript-6">
  import Container from "../../components/common/Container";
  import Toolbar from "../../components/common/Toolbar";
  import ConfigSelect from "./config/ConfigSelect";
  import Operation from "../../components/common/Operation";
  import BaseSelect from "../../components/common/BaseSelect";
  import mysql from "promise-mysql";
  import { BizError } from "../../utils/js/Error";
  import { arrayToOptions } from "../../utils/js/convert";
  import { COLUMNS, SCHEMATA, TABLES } from "./query";
  import TableButton from "../../components/common/TableButton";
  import ModelBuildDialog from "./dialog/ModelBuildDialog";
  import ModelTemplateDialog from "../../components/template-dialog/ModelTemplateDialog";
  import { defaultTemplate } from "./default-template";
  import { MODEL } from "../../res/config-key";

  /**
   * @author 白雨浓
   * @date 2019/6/27 16:12
   *
   * 实体类生成
   **/
  let conn;/*表信息连接*/
  export default {
    name: 'ModelModel',
    components: {
      ModelBuildDialog,
      ModelTemplateDialog, TableButton, BaseSelect, Operation, ConfigSelect, Toolbar, Container
    },
    data() {
      return {
        templateDialog: {
          visible: false,
          defaultTemplate: defaultTemplate,
          cacheKey: MODEL.TEMPLATE,
        },
        buildDialog: {
          visible: false,
          table: {},
          columns: [],
        },
        activeConfig: '',
        databaseOptions: [],
        activeDatabase: '',
        tables: [],
        search: '',
      }
    },
    computed: {
      list() {
        return this.tables.filter(item =>
          !this.search || item.TABLE_NAME.toLowerCase().includes(this.search.toLowerCase())
        );
      }
    },
    methods: {
      async buildClick(table) {
        const columns = await conn.query(...COLUMNS.selectList(table.TABLE_SCHEMA, table.TABLE_NAME));
        this.buildDialog = {
          visible: true,
          table: table,
          columns: columns,
        }
      },
      async handleConfigSelect() {

        this.$$loading.start();
        try {
          conn = await mysql.createConnection({
            ...this.activeConfig,
            database: 'INFORMATION_SCHEMA',
          });

          const items = await conn.query(...SCHEMATA.selectList());
          this.databaseOptions = arrayToOptions(items, 'SCHEMA_NAME', 'SCHEMA_NAME');

        } catch (e) {
          console.log(e);
          throw new BizError('数据库连接错误: ' + e.message, e);
        } finally {
          this.$$loading.close();
        }
      },
      async handleDatabaseChange() {

        this.$$loading.start();

        try {
          this.tables = await conn.query(...TABLES.selectList(this.activeDatabase));
        } catch (e) {
          throw new BizError(e.message, e);
        } finally {
          this.$$loading.close();
        }
      }
    },
    beforeRouteLeave(to, from, next) {
      if (conn) {
        conn.destroy();
        conn = undefined;
      }
      next();
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
    .model {
    }

    .right {
        text-align right
        padding-right 10px

        .select {
            margin 0 10px
        }
    }

    .main {
        width 90%
        margin 20px auto
    }

    .databases-select {
        width 200px
    }
</style>
